package org.jash.shop2202.shop

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jash.shop2202.database.GoodsDao
import org.jash.shop2202.entity.BannerEntity
import org.jash.shop2202.entity.Goods
import org.jash.shop2202.mvvm.BaseViewModel
import org.jash.shop2202.net.ApiService
import org.jash.shop2202.utils.getService
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(val service:ApiService, val dao:GoodsDao): BaseViewModel() {

    val goodsLiveData by lazy { MutableLiveData<List<Goods>>() }
    val searchLiveData by lazy { MutableLiveData<List<Goods>>() }
    val bannerLiveData by lazy {  MutableLiveData<List<BannerEntity>>() }
    fun loadGoods(page:Int, size:Int) {
        viewModelScope.launch {
            try {
                val res = service.getGoodsByCategory(0, page, size)
                if (res.code == 200) {
                    goodsLiveData.postValue(res.data)
                    dao.save(*res.data.toTypedArray())
                } else {
                    failureLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
    fun loadBanner() {
        viewModelScope.launch {
            try {
                val res = service.getBanner()
                if (res.code == 200) {
                    bannerLiveData.postValue(res.data)
                } else {
                    failureLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
    fun search(keyword:String) {
        viewModelScope.launch{
//            try {
//                val res = service.getGoodsByCategory(0, 1, 100)
//                if (res.code == 200) {
//                    searchLiveData.postValue(res.data.filter { keyword in it.goods_desc })
//                } else {
//                    failureLiveData.postValue(RuntimeException(res.message))
//                }
//            } catch (e:Exception) {
//                failureLiveData.postValue(e)
//            }
            try {
                val list = dao.search("%$keyword%")
                searchLiveData.postValue(list)
            }catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
}